package com.ruoyi.common.utils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import sun.misc.BASE64Encoder;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Base64;
import java.util.UUID;

@Component
public class Base64Util {
    @Autowired
    private  QiniuKodoUtil qiniuKodoUtil;

    /**
     　　* 网络图片转换Base64的方法
     　　* @param netImagePath
     　　*/
    public static String netImageToBase64(String picUrl) {
        InputStream is = null;
        try{
            String encoder = "data:image/jpg;base64,"; //定义图片类型，方便前端直接使用
            ByteArrayOutputStream data = new ByteArrayOutputStream();
            URL url = new URL(picUrl);//picUrl为图片地址
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            is = connection.getInputStream();
            byte[] bytes = new byte[1024];
            int len = 0;
            while ((len = is.read(bytes)) != -1){
                data.write(bytes,0,len);
            }
            BASE64Encoder base64Encoder = new BASE64Encoder();
            encoder = encoder +  base64Encoder.encode(data.toByteArray()).replace("\r\n","").trim();//这里去掉结果里面的"\r\n"，也可以不去，但是不去的话需要使用的时候还是要去掉，所以为了方便就先去掉再存储
            return encoder;
        }catch(Exception e){
            e.printStackTrace();
        }finally {
            try {
                is.close();
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }
        return "";
    }


    public  String base64ToUrl(String base64EncodedString) {
        try {
            // 使用Base64解码器解码字符串
            byte[] decodedBytes = Base64.getDecoder().decode(base64EncodedString);
            // 将解码后的字节数组转化为InputStream
            InputStream inputStream = new ByteArrayInputStream(decodedBytes);
            String fileName = UUID.randomUUID().toString().replace("-", "") + ".png";
            String url = qiniuKodoUtil.uploadStream(inputStream, fileName);
            if (StringUtils.isNotBlank(url)) {
                return url;
            } else {
                return "";
            }
        }catch(Exception e){
            e.printStackTrace();
            return "";
        }
    }


}
